package top.shiyiri.reflection3;

import org.junit.Test;
import top.shiyiri.reflection2.Person;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * @author Aunean
 * @date 2022/1/12
 */
/*
获取当前运行时类的属性结构
 */
public class FieldTest {

    @Test
    public void test1() {
        Class<Person> clazz = Person.class;

        //获取属性结构
        //getFields()：获取当前运行时类及其父类中声明为public访问权限的属性
        Field[] fields = clazz.getFields();
        for (Field field: fields) {
            System.out.println(field);
            /*
            public int top.shiyiri.reflection2.Person.id
            public double top.shiyiri.reflection2.Creature.weight
             */
        }

        System.out.println("***********************");

        //getDeclaredFields()：获取当前运行时类中声明的所有属性（不包含父类中声明的属性）
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field de: declaredFields) {
            System.out.println(de);
            /*
            private java.lang.String top.shiyiri.reflection2.Person.name
            int top.shiyiri.reflection2.Person.age
            public int top.shiyiri.reflection2.Person.id
             */
        }
    }

    //权限修饰符 数据类型 变量名
    @Test
    public void test2() {
        Class<Person> clazz = Person.class;
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field de: declaredFields) {
            //1.权限修饰符
            int modifiers = de.getModifiers();
            System.out.print(Modifier.toString(modifiers)+"\t---");

            //2.数据类型
            Class<?> type = de.getType();
            System.out.print(type+"\t---");

            //3.变量名
            System.out.println(de.getName());
            /*
            private	---class java.lang.String	---name
                ---int	---age
            public	---int	---id
             */
        }
    }
}
